<template>
  <basic-container>
    <el-tabs type="border-card" class="tab-font">
      <el-tab-pane label="统计维修搜索"> </el-tab-pane>
      <avue-form ref="form" :option="option" v-model="form">
        <template slot="fromRouteId">
          <el-select v-model="form.fromRouteId" placeholder="不良工序" :loading="selectLoading">
            <el-option v-for="item in fromRouteOptions" :key="item.fromRouteId" :label="item.fromRouteName" :value="item.fromRouteId"></el-option>
          </el-select>
        </template>
        <template slot-scope="{ size }" slot="btn">
          <el-button type="primary" :size="size" class="el-icon-search" @click="handleSubmit" :disabled="loading">搜索</el-button>
          <el-button :size="size" @click="handleCancel" class="el-icon-delete">清空</el-button>
        </template>
      </avue-form>
    </el-tabs>
    <el-tabs type="border-card" class="chart-tab tab-font">
      <el-tab-pane label="统计维修明细"> </el-tab-pane>
      <el-row :gutter="20">
        <el-col :span="12">
          <chart-view class="chart-content" :chart-option="phenomenaOption" :auto-resize="true" width="100%" />
        </el-col>
        <el-col :span="12">
          <chart-view class="chart-content" :chart-option="reasonOption" :auto-resize="true" width="100%" />
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <avue-crud ref="crud" :option="tableOption" :table-loading="loading" :data="data" :page="page" @current-change="currentChange" @size-change="sizeChange">
          <!-- <template slot="menuLeft">
            <el-button type="warning" size="small" icon="el-icon-download" @click="$refs.exportComp.visible = true">导出</el-button>
          </template> -->
          <template slot-scope="{ row }" slot="menu">
            <el-button icon="el-icon-view" size="small" type="text" @click="rowView(row)">详情</el-button>
          </template>
        </avue-crud>
      </el-row>
    </el-tabs>
    <el-dialog title="查看详情" :visible="dialogVisible" append-to-body width="50%" :before-close="handleClose">
      <avue-crud
        ref="crud"
        :option="detailOption"
        :table-loading="detailLoading"
        :data="detailData"
        :page="detailPage"
        @current-change="detailCurrentChange"
        @size-change="detailSizeChange"
      >
      </avue-crud>
    </el-dialog>
    <global-modal-template :visibile.sync="visibile" :option="dialogOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></global-modal-template>
    <common-modal-template ref="commonModalTemplate" :option="dialogOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"></common-modal-template>
    <export-comp
      ref="exportComp"
      data-list-chain="dataList"
      page-api-url="mes-abacus/statMroCenterProduct/top"
      :option="tableOption"
      :page="page"
      :query="query"
      file-name="维修统计报表"
    >
    </export-comp>
  </basic-container>
</template>

<script>
import moment from 'moment/moment';
import ChartView from '@/components/chart/index.vue';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import exportComp from '@/components/export-comp';
import { reasonOption, phenomenaOption, tableOption, detailOption } from '@/views/report/maintenanceStatistice';
import { getNgPhenomenon, getNgCause, getList, getDetail } from '@/api/report/maintenanceStatistics';
import { getProcessRouteByNo } from '@/api/product/station-manage';

export default {
  name: 'maintenanceStatistics',
  components: {
    ChartView,
    GlobalModalTemplate,
    CommonModalTemplate,
    exportComp
  },
  data() {
    return {
      form: {
        examineDate: this.getDefaultTime()
      },
      query: {},
      timer: new Date().getTime(),
      visibile: false,
      dialogOption: {},
      fromRouteOptions: [],
      detailLoading: false,
      dialogVisible: false,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectLoading: false,
      detailPage: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      data: [],
      detailData: [],
      loading: false,
      detailQuery: {},
      reasonOption,
      phenomenaOption,
      tableOption,
      detailOption,
      option: {
        menuPosition: 'left',
        submitBtn: false,
        emptyBtn: false,
        column: [
          {
            label: '时间范围',
            span: 6,
            prop: 'examineDate',
            type: 'daterange',
            format: 'yyyy-MM-dd',
            valueFormat: 'yyyy-MM-dd',
            startPlaceholder: '开始日期',
            endPlaceholder: '结束日期',
            pickerOptions: {
              disabledDate(time) {
                return time.getTime() > Date.now();
              }
            },
            rules: [
              {
                required: true,
                message: '请选择时间范围',
                trigger: 'blur'
              },
              {
                trigger: 'change',
                validator: (rule, value, callback) => {
                  const endTime = value[1];
                  const startTime = value[0];
                  if (moment(endTime).diff(moment(startTime), 'day') > 93) {
                    callback(new Error('查询时间最多为3个月时间'));
                  }
                  callback();
                }
              }
            ]
          },
          {
            label: '工单号',
            prop: 'workOrderNo',
            span: 6,
            type: 'search',
            appendClick: () => {
              this.openWorkOrderCommonModal();
            },
            blur: ({ value }) => {
              if (value) {
                this.findWorkOrderNoByNo(value);
              }
            }
          },
          {
            label: '不良工序',
            prop: 'fromRouteId',
            search: true,
            searchOrder: 4,
            type: 'select',
            dicUrl: '',
            props: {
              label: 'name',
              value: 'id'
            },
            span: 6
          },
          {
            label: '产品编码',
            prop: 'partNo',
            span: 6
          },

          {
            label: '产品名称',
            prop: 'partName',
            span: 6
          },
          {
            label: '不良原因大类',
            prop: 'mainCauseId',
            labelWidth: '120',
            span: 6,
            type: 'select',
            dicUrl: '/api/mes-product/mro-dict/page?dictType=BAD_CAUSE&current=1&size=500',
            props: {
              label: 'name',
              value: 'id'
            },
            dicFormatter: (data) => {
              return data.data.records;
            },
            cascader: ['subName']
          },
          {
            label: '不良现象',
            prop: 'failureName',
            span: 6,
            search: true,
            type: 'search',
            disabled: true,
            appendClick: () => {
              this.openFailureCommonModal();
            }
            // dicUrl: '/api/mes-product/mro/dict/page?dictType=FAILURE&current=1&size=500',
            // props: {
            //   label: 'name',
            //   value: 'id'
            // },
            // dicFormatter: (data) => {
            //   return data.data.records;
            // },
            // cascader: ['subName']
          },
          {
            label: '批次',
            prop: 'workLotNo',
            span: 6
          },
          {
            label: '机型',
            prop: 'workProductModel',
            span: 6
          },
          {
            label: '',
            prop: 'btn',
            span: 6,
            formslot: true
          }
        ]
      }
    };
  },
  mounted() {
    this.onLoad();
  },
  methods: {
    async onLoad() {
      const { examineDate, workOrderNo, fromRouteId, partNo, partName, mainCauseId, failureId } = this.form;
      const { currentPage, pageSize } = this.page;
      const params = {
        current: currentPage,
        size: pageSize,
        startDate: examineDate[0],
        endDate: examineDate[1],
        workOrderNo,
        fromRouteId,
        partName,
        partNo,
        failureId,
        mainCauseId
      };
      this.query = params;
      this.loading = true;
      try {
        getNgPhenomenon(params).then((res) => {
          const data = res.data.data;
          this.setPhenomenaOption(data);
        });
        getNgCause(params).then((res) => {
          const data = res.data.data;
          this.setReasonOption(data);
        });
        getList(params).then((res) => {
          const data = res.data.data;
          this.data = data.records;
          this.page.currentPage = data.current;
          this.page.total = data.total;
          this.page.pageSize = data.size;
        });
        // const ngPhenomenonRes = await getNgPhenomenon(params);
        // const ngPhenomenonData = ngPhenomenonRes.data.data;
        // this.setPhenomenaOption(ngPhenomenonData);
        // const ngCauseRes = await getNgCause(params);
        // const ngCauseData = ngCauseRes.data.data;
        // this.setReasonOption(ngCauseData);
      } catch (e) {
        console.warn(e);
      } finally {
        this.loading = false;
      }
    },
    async getDetailList() {
      const { partNo, fromRouteId, workOrderNo, registryDate } = this.detailQuery;
      const params = { partNo, fromRouteId, workOrderNo, registryDate: moment(registryDate).format('yyyy-MM-DD') };
      this.detailLoading = true;
      try {
        const res = await getDetail(params);
        const data = res.data.data;
        this.detailData = data.records || [];
        this.detailPage.currentPage = data.current;
        this.detailPage.total = data.total;
        this.detailPage.pageSize = data.size;
      } catch (e) {
        console.warn(e);
      } finally {
        this.detailLoading = false;
      }
    },
    getDefaultTime() {
      return [this.$moment(new Date()).subtract(6, 'days').format('yyyy-MM-DD'), this.$moment(new Date()).format('yyyy-MM-DD')];
    },
    handleSubmit() {
      this.$refs.form.validate((valid, done) => {
        if (valid) {
          this.onLoad();
          done();
        }
      });
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
      this.onLoad();
    },
    detailCurrentChange(currentPage) {
      this.detailPage.currentPage = currentPage;
      this.getDetailList();
    },
    detailSizeChange(pageSize) {
      this.detailPage.pageSize = pageSize;
      this.getDetailList();
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
      this.onLoad();
    },
    handleCancel() {
      this.$refs.form.resetForm();
      this.data = [];
      this.$set(this.phenomenaOption.xAxis, 'data', []);
      this.$set(this.phenomenaOption.series[0], 'data', []);
      this.$set(this.phenomenaOption.series[1], 'data', []);
      this.$set(this.reasonOption.xAxis, 'data', []);
      this.$set(this.reasonOption.series[0], 'data', []);
      this.$set(this.reasonOption.series[1], 'data', []);
    },
    setPhenomenaOption(data = []) {
      const xAxisData = data.map((item) => item.name);
      const quantitySeries = data.map((item) => item.quantity);
      const percentageSeries = data.map((item) => item.percentage);
      this.$set(this.phenomenaOption.xAxis, 'data', xAxisData);
      this.$set(this.phenomenaOption.series[0], 'data', quantitySeries);
      this.$set(this.phenomenaOption.series[1], 'data', percentageSeries);
    },
    setReasonOption(data = []) {
      const xAxisData = data.map((item) => item.name);
      const quantitySeries = data.map((item) => item.quantity);
      const percentageSeries = data.map((item) => item.percentage);
      this.$set(this.reasonOption.xAxis, 'data', xAxisData);
      this.$set(this.reasonOption.series[0], 'data', quantitySeries);
      this.$set(this.reasonOption.series[1], 'data', percentageSeries);
    },
    async rowView(row) {
      this.detailQuery = row;
      await this.getDetailList();
      this.dialogVisible = true;
    },
    handleClose() {
      this.dialogVisible = false;
    },
    openWorkOrderCommonModal() {
      // 生产订单
      this.modalName = 'workOrderModal';
      this.visibile = true;
      this.dialogOption = {
        modalTitle: '选择工单信息（双击进行选择）',
        url: '/api/mes-product/work-order/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchLabelWidth: 90,
        templateName: 'WORKORDER'
      };
    },
    openFailureCommonModal() {
      this.$refs.commonModalTemplate.showModal();
      this.modalName = 'failureCode';
      this.dialogOption = {
        modalTitle: '选择不良代码信息（双击进行选择）',
        url: '/api/mes-product/mro-dict/page?dictType=BAD_PHENOMENON',
        isPage: true,
        index: false,
        rowSelectionType: 'single',
        searchLabelWidth: 100,
        columnDefs: [
          {
            label: '不良代码',
            prop: 'code',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良代码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '不良现象描述',
            prop: 'name',
            search: true,
            row: true,
            span: 24,
            rules: [
              {
                required: true,
                message: '请输入不良现象描述',
                trigger: 'blur'
              }
            ]
          }
        ]
      };
    },
    // 获取选择的物料模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'workOrderModal':
          this.visibile = false;
          this.form.workOrderNo = this._get(rowData, 'orderNo', '');
          this.findWorkOrderNoByNo(this.form.workOrderNo);
          break;
        case 'failureCode':
          this.form.failureName = this._get(rowData, 'name', '');
          this.form.failureId = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    // 根据工单编号获取工序
    findWorkOrderNoByNo(workorderNo) {
      this.fromRouteOptions = [];
      this.selectLoading = true;
      getProcessRouteByNo({ workorderNo })
        .then((res) => {
          this.fromRouteOptions = res.data.data.map((d) => {
            return {
              fromRouteCode: d.code,
              fromRouteId: d.id,
              fromRouteName: d.name
            };
          });
        })
        .finally(() => {
          this.selectLoading = false;
        });
    },
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style scoped lang="scss">
.chart-tab {
  margin-top: 24px;
  height: calc(100vh - 385px);
  overflow-y: scroll;
}
.tab-font {
  ::v-deep .el-tabs__item {
    color: #606266 !important;
    font-weight: bold;
  }
}
::v-deep .el-dialog__body {
  .el-card__body {
    .avue-crud__menu {
      display: none;
    }
  }
}
</style>
